from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import HTTPBearer
from fastapi.staticfiles import StaticFiles
from sqlalchemy.orm import Session
import uvicorn
import os

from database import get_db, engine
from models import Base
from routers import auth, posts, users, comments
from config import settings

# 创建数据库表
Base.metadata.create_all(bind=engine)

# 初始化默认数据
def init_default_data():
    """初始化默认数据（分类等）"""
    try:
        from init_data import init_default_categories
        init_default_categories()
    except Exception as e:
        print(f"初始化默认数据时出现错误: {e}")

# 启动时初始化
init_default_data()

app = FastAPI(
    title="博客系统 API",
    description="基于 FastAPI 的现代化博客系统后端服务",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    redirect_slashes=False  # 禁用自动重定向斜杠
)

# CORS 配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.ALLOWED_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(auth.router, prefix="/api/auth", tags=["认证"])
app.include_router(posts.router, prefix="/api/posts", tags=["文章"])
app.include_router(users.router, prefix="/api/users", tags=["用户"])
app.include_router(comments.router, prefix="/api", tags=["评论"])

# 静态文件服务
if not os.path.exists("uploads"):
    os.makedirs("uploads")
app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")

@app.get("/")
async def root():
    return {"message": "博客系统 API 服务正在运行", "version": "1.0.0"}

@app.get("/health")
async def health_check():
    return {"status": "healthy"}

if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True
    )
